# -*- encoding: utf-8 -*-
"""
    app.py
    :description: 一个框架
    :date: 2020/09/03 19:36:48
    :version      :1.0
    :copyright: (c) 2020 by enjoyZHou
"""
import asyncio
from threading import Thread
from starlette.responses import HTMLResponse
from starlette.requests import Request
# from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles, FileResponse
from starlette.middleware.gzip import GZipMiddleware
from typing import Optional
from fastapi import FastAPI
from .routers.blueprints import register_blueprint

app = FastAPI(
    title="QSDnde",
    description="This QSDnde API",
    version="0.2.0",)
app.add_middleware(GZipMiddleware, minimum_size=2048)
app.mount("/static", StaticFiles(directory="ui/dist/static"), name="static")
# templates = Jinja2Templates(directory='web/templates')


# @app.get("/api")
# async def api_root(request: Request):
#     return f'{request.headers.get("host")}'

# 注册蓝图
register_blueprint(app)

# 把剩余的转发到静态页面


# @app.get("/{path:path}", include_in_schema=False, response_class=HTMLResponse)
# async def web(path: str, request: Request):
#     return templates.TemplateResponse('index.html', {'request': request, 'path': path})

@app.get("/favicon.ico", include_in_schema=False)
async def favicon(request: Request):
    return FileResponse('ui/dist/favicon.ico', media_type='image/vnd.microsoft.icon')


@app.get("/{path:path}", include_in_schema=False, response_class=HTMLResponse)
async def web(path: str, request: Request):
    return FileResponse('ui/dist/index.html')


def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()


def add_task(loop):
    """
    添加线程循环事件任务
    :param loop:
    :return:
    """
    def func(aw_func):
        asyncio.run_coroutine_threadsafe(aw_func, loop)
    return func


@app.on_event("startup")
async def on_startup() -> None:
    loop = asyncio.new_event_loop()
    t = Thread(target=start_loop, args=(loop,))
    t.setDaemon(True)  # 守护主线程，主线程结束后，守护子线程随之中止。
    t.start()
    app.state.WS_CLIENT = None
    app.state.event_loop = loop
    app.state.event_loop_add_task = add_task(loop)


@app.on_event("shutdown")
async def on_shutdown() -> None:
    app.state.event_loop.stop()
